package com.fractalist.base.core.utils;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;

//import sun.misc.BASE64Encoder;

public class Tools {

	/**
	 * 获取properties值
	 * @param key
	 * @param propsFile
	 * @return
	 */
	public String getProp(String key,String propsFile) {
		String retVal = null;
		InputStream is = getClass().getResourceAsStream(propsFile);
		Properties props = new Properties();
		try {
			props.load(is);
			retVal = props.getProperty(key);
			if (retVal == null)
				retVal = "";
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return retVal;
	}
	
	/**
	 * 读 properties文件
	 * 
	 * @param property
	 * @param propPath
	 * @return
	 */
	public static Map<String, String> propertiesHandle(
			Map<String, String> property, String propPath) {

		BufferedReader br = null;
		try {

			br = new BufferedReader(new InputStreamReader(new FileInputStream(
					propPath), "UTF-8"));
		} catch (Exception e1) {
			e1.printStackTrace();
			return null;
		}

		Properties prop = new Properties();

		try {
			prop.load(br);
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}

		@SuppressWarnings("rawtypes")
		Iterator it = property.entrySet().iterator();

		String value = "";
		while (it.hasNext()) {
			@SuppressWarnings("unchecked")
			Entry<String, String> entry = (Entry<String, String>) it.next();
			value = prop.getProperty((String) entry.getKey());
			if (value == null) {
				value = "";
			}
			property.put((String) entry.getKey(), value);
		}
		try {
			br.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return property;
	}

	/**
	 * BASE64编码转换
	 * 
	 * @param str
	 * @param encode
	 * @return
	 */
/*	public static String base64Encoder(String str, String encode) {

		byte[] b = null;
		try {
			if (encode != null) {
				b = str.getBytes(encode);
			} else {
				b = str.getBytes();
			}
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			return null;
		}

		str = new BASE64Encoder().encode(b);

		return str;

	}*/

/*	public static String base64Encoder(String str) {
		return base64Encoder(str, null);
	}

	public static String base64Encoder(byte[] b) {
		return new BASE64Encoder().encode(b);
	}*/

	/**
	 * List转为String<br>
	 * 例: aa,bb,cc,dd
	 * 
	 * @param list
	 *            List
	 * @param space
	 *            间隔符
	 * @return
	 */
	public static String listToStr(List<String> list, String space) {

		StringBuilder strb = new StringBuilder();
		//System.out.println(list);
		for (int i = 0; i < list.size() - 1; i++) {
			strb.append(list.get(i));
			strb.append(space);
		}
		strb.append(list.get(list.size() - 1));
		return strb.toString();
	}

	/**
	 * 获取文件扩展名
	 * 
	 * @param name
	 * @return
	 */
	public static String getExt(String name) {
		int index = name.indexOf(".");
		return name.substring(++index);
	}

	/**
	 * 休眼一段是时间
	 * 
	 * @param time
	 */
	public static void sleep(int time) {
		try {
			Thread.sleep(time);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * 创建线程池
	 * 
	 * @param corePoolSize
	 * @param maxImumPoolSize
	 * @param keepAliveTime
	 * @param queueNumber
	 * @return
	 */
	public static ThreadPoolExecutor buildThreadPool(String corePoolSize,
			String maxImumPoolSize, String keepAliveTime, String workQueue) {

		return new ThreadPoolExecutor(Integer.parseInt(corePoolSize),
				Integer.parseInt(maxImumPoolSize),
				Integer.parseInt(keepAliveTime), TimeUnit.SECONDS,
				new ArrayBlockingQueue<Runnable>(Integer.parseInt(workQueue)),
				new ThreadPoolExecutor.CallerRunsPolicy());

	}

	/**
	 * 生成随即密码
	 * 
	 * @param pwd_len
	 *            生成的密码的总长度
	 * @return 密码的字符串
	 */
	public static String genRandomStr(int pwd_len) {
		// 35是因为数组是从0开始的，26个字母+10个数字
		final int maxNum = 36;
		int i; // 生成的随机数
		int count = 0; // 生成的密码的长度
		final char[] str = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
				'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
				'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7',
				'8', '9', '_', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
				'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
				'V', 'W', 'X', 'Y', 'Z' };

		StringBuilder pwd = new StringBuilder(pwd_len);
		Random r = new Random();
		while (count < pwd_len) {
			// 生成随机数，取绝对值，防止生成负数，

			i = Math.abs(r.nextInt(maxNum)); // 生成的数最大为36-1

			if (i >= 0 && i < str.length) {
				pwd.append(str[i]);
				count++;
			}
		}

		return pwd.toString();
	}

	/**
	 * 获取当前时间
	 * 
	 * @param format
	 * @return
	 */
	public static String getCurrentDate(String format) {
		SimpleDateFormat bartDateFormat = new SimpleDateFormat(format);

		Date date = new Date();
		return bartDateFormat.format(date);
	}

	public static void main(String args[]) throws Exception {
		Tools t = new Tools();

		String a = "sdfasdfasdfasdfsadfsadf";

		//System.out.println(t.base64Encoder(a, "GBK"));

	}

	/**
	 * 获取ip
	 * @param request
	 * @return
	 */
	public String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
}
